<template>
	<div class="shiftDoctor">
		<span class="tittle">康恒医院医生轮班信息表</span>
		<div class="filter-container">
			<el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="医生姓名"
				v-model="searchName"></el-input>
			<el-select clearable class="filter-item" style="width: 130px" placeholder="医生科室" v-model="searchDepartment">
				<el-option v-for="item in typeOptions" :key="item.key" :label="item.display_name" :value="item.key">
				</el-option>
			</el-select>
			<el-select clearable class="filter-item" style="width: 130px" placeholder="时间段" v-model="searchTimes">
				<el-option v-for="item in times" :key="item.key" :label="item.display_name" :value="item.display_name">
				</el-option>
			</el-select>
			<el-button class="filter-item" type="primary" icon="search" @click="handelSearch">搜索</el-button>
			<el-button type="primary" icon="" @click="getAll">显示全部</el-button>
			<el-button class="filter-item" type="primary" @click="handelCreate" icon="edit">添加</el-button>
			<el-button class="filter-item" type="primary" icon="document" @click="handleDownload">导出</el-button>
		</div>
		
		<el-table v-if="shiftList" :data="shiftList" border style="width: 100%" height="460">
			<el-table-column prop="id" fixed label="编号" width="120"></el-table-column>
			<el-table-column prop="date" fixed label="日期" width="120"></el-table-column>
			<el-table-column prop="dates" label="时段" width="200"></el-table-column>
			<el-table-column prop="name" label="姓名" width="150"></el-table-column>
			<el-table-column prop="sex" label="性别" width="150"></el-table-column>
			<el-table-column prop="office" label="科室" width="150"></el-table-column>
			<el-table-column prop="shiftId" label="医生编号" width="150"></el-table-column>
			<el-table-column prop="attendance" label="出勤情况" width="120" v-model="listQuery.type"></el-table-column>
			<el-table-column prop="signatory" label="主任签名" width="120"></el-table-column>
			<el-table-column align="center" label="操作">
				<template scope="scope">
					<el-button size="small" type="primary" @click="handleEdit(scope.$index)">编辑</el-button>
					<el-button size="small" type="danger" @click="handleDelete(scope.$index)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--  添加信息表单 -->
		<el-dialog title="添加信息" :visible.sync="dialogFormVisible">
			<el-form class="small-space" :model="form" label-position="left" label-width="70px"
				style='width: 500px; margin-left:50px;'>
				<el-form-item label="姓名">
					<el-select style="width: 130px" placeholder="必填" v-model="form.name" @change="handleSelectChange">
						<el-option v-for="item in shiftListNurse" :key="item.id" :label="item.name + ' ' + item.id + ' ' + item.sex"
							:value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="日期">
					<el-input v-model="form.date" placeholder="格式: YYYY-MM-DD"></el-input>
				</el-form-item>
				<el-form-item label="值班时间">
					<el-select v-model="form.dates" placeholder="请选择值班时间">
						<el-option label="早班 8：00-16：00" value="早班 8：00-16：00"></el-option>
						<el-option label="白班 8：00-17：00" value="白班 8：00-17：00"></el-option>
						<el-option label="小夜 16：00-24：00" value="小夜 16：00-24：00"></el-option>
						<el-option label="大夜 24：00-8：00" value="大夜 24：00-8：00"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="科室">
					<el-select style="width: 130px" placeholder="必填" v-model="form.office">
						<el-option v-for="item in typeOptions" :key="item.key" :label="item.display_name"
							:value="item.key">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="主任">
					<el-input v-model="form.signatory"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogFormVisible = false">取 消</el-button>
				<el-button type="primary" @click="handleCreateSubmit">确 定</el-button>
				<el-button type="primary" @click="resetForm('form')">重置</el-button>
			</div>
		</el-dialog>

		<!-- 编辑信息表单 -->
		<el-dialog title="修改值班信息" :visible.sync="dialogFormEditVisible">
			<el-form class="small-space" :model="form" label-position="left" label-width="70px"
				style='width: 500px; margin-left:50px;'>
				<el-form-item label="医生编号">
					<span>{{shiftListEdit.shiftId}}</span>
				</el-form-item>
				<el-form-item label="医生姓名">
					<span>{{shiftListEdit.name}}</span>
				</el-form-item>
				<el-form-item label="日期">
					<el-input v-model="shiftListEdit.date" placeholder="格式: YYYY-MM-DD"></el-input>
				</el-form-item>
				<el-form-item label="值班时间">
					<el-select v-model="shiftListEdit.dates" placeholder="请选择值班时间">
						<el-option label="早班 8：00-16：00" value="早班 8：00-16：00"></el-option>
						<el-option label="白班 9：00-17：00" value="白班 9：00-17：00"></el-option>
						<el-option label="小夜 16：00-24：00" value="小夜 16：00-24：00"></el-option>
						<el-option label="大夜 24：00-8：00" value="大夜 24：00-8：00"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="科室">
					<el-select class="filter-item" style="width: 130px" placeholder="必填" v-model="shiftListEdit.office">
						<el-option v-for="item in typeOptions" :key="item.key" :label="item.display_name"
							:value="item.key">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="出勤情况">
					<el-select v-model="shiftListEdit.attendance" placeholder="必填">
						<el-option label="上班" value="上班"></el-option>
						<el-option label="休息" value="休息"></el-option>
						<el-option label="请假" value="请假"></el-option>
						<el-option label="早退" value="早退"></el-option>
						<el-option label="迟到" value="迟到"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="主任">
					<el-input v-model="shiftListEdit.signatory" placeholder="必填"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogFormEditVisible = false">取 消</el-button>
				<el-button type="primary" @click="handleEditSubmit">确 定</el-button>
			</div>
		</el-dialog>

		<div class="block">
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
				:current-page.sync="pageNum" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize"
				layout="total, sizes, prev, pager, next, jumper" :total="totalNum">
			</el-pagination>
		</div>
	</div>

</template>

<script type="text/ecmascript-6">
	import Vue from 'vue';
	import {
		debounce
	} from 'lodash';
	import {
		api
	} from '../../../global/api.js';
	export default {
		data() {
			return {
				shiftList: [],
				shiftListEdit: [],
				Index: [],
				shiftListNurse: [],
				searchName: '',
				searchDepartment: '',
				listQuery: {
					type: null
				},
				dialogFormVisible: false,
				dialogFormEditVisible: false,
				form: {
					id: '',
					name: '',
					date: '',
					dates: '',
					shiftId: '',
					attendance: '',
					office: '',
					sex: '',
					signatory: ''
				},
				typeOptions: [{
						key: '外科',
						display_name: '外科'
					},
					{
						key: '骨科',
						display_name: '骨科'
					},
					{
						key: '精神科',
						display_name: '精神科'
					},
					{
						key: '急诊',
						display_name: '急诊'
					},
					{
						key: '妇科',
						display_name: '妇科'
					},
					{
						key: '胸心外科',
						display_name: '胸心外科'
					},
					{
						key: '口腔科',
						display_name: '口腔科'
					},
					{
						key: '普外科',
						display_name: '普外科'
					}
				],
				searchTimes: '',
				times: [{
						key: '早班',
						display_name: '早班：6:00~17:00'
					},
					{
						key: '日班',
						display_name: '日班：10：00~21：00'
					},
					{
						key: '小夜',
						display_name: '小夜：16：00~00：00'
					},
					{
						key: '大夜',
						display_name: '大夜：00：00~8：00'
					}
				],
				// 当前页
				pageNum: 1,
				// 一页显示的行数
				pageSize: 10,
				// 总行数
				totalNum: 0,
				cache: {}
			};
		},
		methods: {
			// 获取护士值班
			init() {
				let that = this;
				let cacheKey = `${that.pageNum}-${that.pageSize}-${that.searchDepartment}-${that.searchName}-${that.searchTimes}`;
				if (that.cache[cacheKey]) {
					that.shiftList = that.cache[cacheKey].data;
					that.totalNum = that.cache[cacheKey].count;
					return;
				}
				//查看所有医生轮班信息
				let API = "http://localhost:8088/getShiftlist";
				this.$http.get(API, {
					params: {
						"pageNum": that.pageNum,
						"pageSize": that.pageSize,
						"searchDepartment": that.searchDepartment,
						"searchName": that.searchName,
						"searchTimes": that.searchTimes
					}
				}).then((response) => {
					for (var i = 0; i < response.body.data.length; i++) {
						if (response.body.data[i].sex == 1) {
							response.body.data[i].sex = "男";
						} else {
							response.body.data[i].sex = "女";
						}
						const dateString = response.body.data[i].date;
						const date = new Date(dateString);
			
						const year = date.getFullYear();
						const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以要加1
						const day = String(date.getDate()).padStart(2, '0');
			
						const formattedDate = `${year}-${month}-${day}`;
			
						response.body.data[i].date = formattedDate;
					}
					that.shiftList = response.body.data;
					that.totalNum = response.body.count;
					that.cache[cacheKey] = {
						data: response.body.data,
						count: response.body.count
					}; // 缓存数据
					console.log(response);
				}, response => {
					this.$message({
						message: '数据请求失败',
						type: 'error'
					});
				});
			},
			
			// 编辑
			handleEdit(index) {
				this.dialogFormEditVisible = true;
				this.Index = index;
				this.shiftListEdit = {
					...this.shiftList[index]
				};
			},
			
			// 修改轮班
			handleEditSubmit() {
				let that = this;
				// 检查空值
				const requiredFields = ['name', 'date', 'dates', 'office', 'attendance', 'signatory'];
				for (let field of requiredFields) {
					if (!that.shiftListEdit[field]) {
						if (field == 'name') {
							field = "姓名";
						} else if (field == 'date') {
							field = "日期";
						} else if (field == 'dates') {
							field = "值班时间";
						} else if (field == 'office') {
							field = "科室";
						} else if (field == 'attendance') {
							field = "出勤情况";
						} else if (field == 'signatory') {
							field = "护士长";
						}
						this.$message({
							message: `${field} 不能为空`,
							type: 'error'
						});
						return;
					}
				}
			
				// 验证日期格式
				const datePattern = /^\d{4}-\d{2}-\d{2}$/;
				if (!datePattern.test(that.shiftListEdit.date)) {
					this.$message({
						message: '日期格式不正确，请使用 YYYY-MM-DD 格式',
						type: 'error'
					});
					return;
				}
			
				if (that.shiftListEdit.sex == "男") {
					that.shiftListEdit.sex = 1;
				} else {
					that.shiftListEdit.sex = 2;
				}
			
				// 提交表单
				let API = "http://localhost:8088/updateShiftlist";
				that.$http.post(API, that.shiftListEdit).then((response) => {
					that.dialogFormEditVisible = false;
			
					if (that.shiftListEdit.sex == 1) {
						that.shiftListEdit.sex = "男";
					} else {
						that.shiftListEdit.sex = "女";
					}
			
					Vue.set(that.shiftList, that.Index, {
						...that.shiftListEdit
					});
					that.init();
					this.$message({
						message: '轮班信息修改成功！',
						type: 'success'
					});
				}, (response) => {
					console.log(this.shiftListEdit);
					this.$message.error('轮班信息修改失败');
				});
			},
			
			// 搜索
			handelSearch: debounce(function() {
				this.init();
			}, 220), // 220毫秒防抖
			
			// 显示全部
			getAll() {
				this.searchName = '';
				this.searchDepartment = '';
				this.init();
			},
			
			// 导出信息表
			handleDownload() {
				// 导出
				var vm = this;
				require.ensure([], () => {
					const {
						export_json_to_excel
					} = require('vendor/Export2Excel');
					const tHeader = ['轮班日期', '时段', '姓名', '性别', '科室', '医生编号', '出勤情况', '主任签名'];
					const filterVal = ['date', 'dates', 'name', 'sex', 'office', 'shiftId', 'attendance',
						'signatory'
					];
					const shiftList = vm.shiftList;
					const data = vm.formatJson(filterVal, shiftList);
					export_json_to_excel(tHeader, data, '医生轮班信息列表excel');
				});
			},
			formatJson(filterVal, jsonData) {
				return jsonData.map(v => filterVal.map(j => v[j]));
			},
			
			// 删除
			handleDelete(index) {
				let that = this;
				this.$confirm('此操作将删除该轮班信息, 是否删除?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					let API = "http://localhost:8088/deleteShiftlist";
					that.$http.post(API, that.shiftList[index].id).then((response) => {
						// 从 that.shiftList 数组中移除该项
						that.shiftList.splice(index, 1);
						// 更新总行数
						that.totalNum -= 1;
						that.$message({
							message: '轮班信息删除成功',
							type: 'success'
						});
					}).catch((error) => {
						that.$message.error('轮班信息删除失败');
					});
				}).catch(() => {
					that.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},

			// 添加
			handelCreate() {
				this.dialogFormVisible = true;
				this.formClear();
			},

			// 添加提交
			handleCreateSubmit() {
				// 检查空值
				const requiredFields = ['name', 'date', 'dates', 'office'];
				for (let field of requiredFields) {
					if (!this.form[field]) {
						if (field == 'name') {
							field = "姓名";
						} else if (field == 'date') {
							field = "日期";
						} else if (field == 'dates') {
							field = "值班时间";
						} else if (field == 'office') {
							field = "科室";
						}
						this.$message({
							message: `${field} 不能为空`,
							type: 'error'
						});
						return;
					}
				}

				// 验证日期格式
				const datePattern = /^\d{4}-\d{2}-\d{2}$/;
				if (!datePattern.test(this.form.date)) {
					this.$message({
						message: '日期格式不正确，请使用 YYYY-MM-DD 格式',
						type: 'error'
					});
					return;
				}

				// 提交表单
				let API = "http://localhost:8088/insertShiftlist";
				this.$http.post(API, this.form).then((response) => {
					this.dialogFormVisible = false;
					this.totalNum += 1;
					this.$message({
						message: '轮班信息添加成功！',
						type: 'success'
					});
				}, response => {
					console.log(this.form);
					this.$message({
						message: '轮班信息添加失败',
						type: 'error'
					});
				});
			},

			// 清空表单
			formClear() {
				this.form = {
					name: '',
					date: '',
					dates: '',
					shiftId: '',
					attendance: '',
					office: '',
					sex: '',
					signatory: ''
				};
			},

			// 重置表单
			resetForm() {
				this.form = {
					name: '',
					date: '',
					dates: '',
					shiftId: '',
					attendance: '',
					office: '',
					sex: '',
					signatory: ''
				};
			},

			// 点击切换每页显示多少行
			handleSizeChange(val) {
				this.pageSize = val;
				console.log(`每页 ${val} 条`);
				this.init();
			},
			// 点击切换页
			handleCurrentChange(val) {
				this.pageNum = val;
				console.log(`当前页: ${val}`);
				this.init();
			},

			handleSelectChange(selectedId) {
				const selectedNurse = this.shiftListNurse.find(nurse => nurse.id === selectedId);
				if (selectedNurse.sex == "男") {
					selectedNurse.sex = 1;
				} else {
					selectedNurse.sex = 2;
				}
				if (selectedNurse) {
					this.form.shiftId = selectedNurse.id;
					this.form.name = selectedNurse.name;
					this.form.sex = selectedNurse.sex;
				}
				if (selectedNurse.sex == 1) {
					selectedNurse.sex = "男";
				} else {
					selectedNurse.sex = "女";
				}
			}
		},
		mounted() {
			this.init();
		},
		created() {
			// 获取医生
			let that = this;
			let API = "http://localhost:8088/getDoctor";
			this.$http.get(API, {
				params: {
					"pageNum": 1,
					"pageSize": 10000,
					"search": ''
				}
			}).then((response) => {
				for (var i = 0; i < response.body.data.length; i++) {
					if (response.body.data[i].sex == 1) {
						response.body.data[i].sex = "男";
					} else {
						response.body.data[i].sex = "女";
					}
					const dateString = response.body.data[i].date;
					const date = new Date(dateString);
			
					const year = date.getFullYear();
					const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以要加1
					const day = String(date.getDate()).padStart(2, '0');
			
					const formattedDate = `${year}-${month}-${day}`;
			
					response.body.data[i].date = formattedDate;
			
					that.shiftListNurse[i] = {
						id: response.body.data[i].id,
						name: response.body.data[i].name,
						sex: response.body.data[i].sex
					};
				}
				console.log(that.shiftListNurse);
			}, response => {
				this.$message({
					message: '数据请求失败',
					type: 'error'
				});
			});
		}
	};
</script>

<style>
	.shiftDoctor .block {
		position: absolute;
	}

	.shiftDoctor .tittle {
		display: block;
		text-align: center;
		font-size: 24px;
		line-height: 80px;
	}

	.shiftDoctor .search {
		margin-bottom: 30px;
	}
</style>